/**
 * jQuery EasyUI 自定义扩展选择控件
 * TiddlerCJ 
 */
(function($){
	/**人员选择控件扩展*/
	$.parser.plugins.push("choosebox");
    $.fn.choosebox = function (options, param) {
        //当options为字符串时，说明执行的是该插件的方法。
        if (typeof options == "string") { return $.fn.textbox.apply(this, arguments); }
        options = options || {};

        return this.each(function () {
            var jq = $(this);
            var opts = $.extend({}, $.fn.textbox.parseOptions(this), options);
            if(opts.boxUrl || opts.modleName){
            	 var boxUrl = "/console/#modleName#/choosebox";
            	 boxUrl = opts.boxUrl || boxUrl.replace("#modleName#", opts.modleName) || '';
            	 var inputName = jq.attr("name") || jq.attr("id") ;
            	 opts.valueField = opts.valueField || opts.textField;
            	 var readonly =  opts.readonly && true;
            	 /*附带属性*/
            	 var attr =  opts.attr;
            	 if(readonly==false){
            		 //console.log(jq.attr("class"));
            		 //$("input[class=textbox-text]",jq.next("span")).removeAttr("readonly");
            		 //jq.parent().find(".textbox-text").removeAttr("readonly");
            		 //console.log(jq.parent().html());
            		 //textbox-text validatebox-text validatebox-readonly validatebox-invalid textbox-prompt
            	 }
            	 opts = $.extend(true, {
                 	prompt:'点击选择按钮...',
                 	buttonText:'选择',
                 	buttonIcon:'icon-search',
                 	editable: false,
                 	callback: null,
                 	onClickButton:function(){
                 		var _$ = top.$ ||  parent.$ || $;
                 		var userDialog = _$("<div/>").dialog("openWin", { 
                 		    title: opts.boxTitle || '通用选择框',   
                 		    width: opts.boxWidth || 650,   //自定义弹出框宽度和高度优先 
                 		    height: opts.boxHeight || 450,   
                 		    href : boxUrl,
                 		    data: { singleSelect : opts.singleSelect || false, jq: jq },
                 		    buttons : [
                 		        {
	     		            	   text : "确定", iconCls : "icon-ok", handler : function() {
	     		            		   var rows = userDialog.iframeWindow.choose() , len = rows.length || 0 ;
	     		            		   var result = { valueField:'', textField:'' };
	     		            		   if(len>0 && opts.textField){
	     		            				var valueField = [],textField = [],attrVal = [];
	     		            				
	     		            				$.each(rows,function(index,row){
	     		            					valueField.push(row[opts.valueField]); textField.push(row[opts.textField]);
	     		            					attrVal.push(row[opts.attr]);
	     		            				});
	     		            				result = { 
	     		            					valueField: valueField.join(","), 
	     		            					textField: textField.join(","),
	     		            					attr : attrVal.join(",")
	     		            				};
	     		            				/*设置值控件值*/
	     		            				jq.textbox('setValue', result.valueField); 
	     		            				jq.textbox('setText', result.textField);
	     		            				
	     		            				/*设置附带属性值*/
	     		            				$("input[name="+ attr +"]").val(result.attr);
	     		            		   }else{
	     		            			   jq.textbox('setValue', ""); 
	     		            			   jq.textbox('setText', "");
	     		            		   }
	     		            		 
	     		            		   if(opts.callback){
	     		            			  opts.callback(rows);
	     		            		   }
	     		            		   /*
	     		            		   $("input[name="+ inputName +"]").val(result.valueField);
	     		            		   $("input[name="+ inputName+"_valueField" +"]").val(result.valueField);
	     		            		   $("input[name="+ inputName+"_textField" +"]").val(result.textField);
	     		            		   */
	     		            		   userDialog.dialog('close');
	     		            	   }
                 		        },
     							{
     								text : "关闭", iconCls : "icon-no", handler : function() {
     									userDialog.dialog('close');
     								}
     							}
                 		    ]
                 		});
                 		userDialog.dialog("center");
                 	}
                 }, opts);
            }else{
            	alert('choosebox控件未配置url地址'); 
            }
            $.fn.textbox.call(jq, opts);
            
            //jq.textbox('setText', '');
            
            /*异步数据回显*/
            setTimeout(function(){
            	var value = opts.value || jq.textbox('getValue') || null;
            	if(value && opts.modleName && opts.textField && opts.textField !=opts.valueField){
            		var echoUrl = "/console/"+ opts.modleName +"/echo" ;
            		$.getJSON(echoUrl, { echoValue: value, textField:opts.textField, idField:opts.valueField } ,function(json){
                		json = json || []; 
                		var text = [];
                		$.each(json,function(index,item){
                			text.push(item[opts.textField]);
                		});
                		text = text.join(",") ;
                		if(text!=""){
                			jq.textbox('setText', text);
                		}
    	        	});
            	}
            },100);
        });
    };
	
	
    /**
     * chooseiconbox扩展
     */
    $.parser.plugins.push("chooseiconbox");
    $.fn.chooseiconbox = function (options, param) {
    	var chooseiconboxP = {
			chooseboxUrl : '/console/icon/choosebox'
    	};
        //当options为字符串时，说明执行的是该插件的方法。
        if (typeof options == "string") { return $.fn.textbox.apply(this, arguments); }
        options = options || {};

        return this.each(function () {
            var jq = $(this);
            var opts = $.extend({}, $.fn.textbox.parseOptions(this), options);
            
            var inputName = jq.attr("name") || jq.attr("id");
            var myopts = $.extend(true, {
            	prompt:'请选择图标...',
            	buttonText:'选择',
            	buttonIcon:'icon-search',
            	editable: false,
            	onClickButton:function(){
            		var _$ = top.$ ||  parent.$ || $;
            		var iconDialog = _$("<div/>").dialog("openWin", {
            		    title: '图标选择',    
            		    width: 650,    
            		    height: 450,   
            		    href : chooseiconboxP.chooseboxUrl,
            		    onBeforeClose:function(){
            		    	var icon = iconDialog.chooseiconbox || '';
            		    	if(icon.length>0){
            		    		jq.textbox('setValue', icon);
            		    		jq.textbox('setText', icon);
            		    		jq.next("span").find(".l-btn-icon").attr("class","l-btn-icon "+ icon);
            		    	}
            		    },
            		    buttons : [
							{
								text : "关闭", iconCls : "icon-no", handler : function() {
									iconDialog.dialog('close');
								}
							}
            		    ]
            		});
            		iconDialog.dialog("center");
            	}
            }, opts);
            $.fn.textbox.call(jq, myopts);
            setTimeout(function(){
            	var value = jq.textbox('getValue') || '';
            	if(value.length>0){
            		jq.next("span").find(".l-btn-icon").attr("class","l-btn-icon "+ value);
            	}
            },100);
        });
    };
    /**
     * autoCode自定义扩展
     */
    $.parser.plugins.push("autoCode");
    $.fn.autoCode = function (options, param) { 
        if (typeof options == "string") { return $.fn.textbox.apply(this, arguments);}
        options = options || {};
        return this.each(function(){
            var jq = $(this);
            var opts = $.extend({readonly:false}, $.fn.textbox.parseOptions(this), options);
            /*异步拉取自动生成代码*/
            function aotoCode(myopts){
            	if(myopts.prefix){
            		var url = "/console/"+ myopts.prefix +"/autoCode" ;
            		$.getJSON(url, { suffix: myopts.suffix,timestamp: (myopts.timestamp ||'')  } ,function(json){
            			if(json && json.flag){
            				jq.textbox('setText', json.data.code);
            				jq.textbox('setValue', json.data.code);
            			}
            		});
            	}
            }
            
            var myopts = {};
            if(opts.readonly==false){
            	myopts = $.extend(true, {
            		buttonText:'刷新',
            		buttonIcon:'icon-reload',
            		editable: false,
            		onClickButton:function(){
            			aotoCode(myopts);
            		}
            	}, opts);
            }else{
            	myopts = opts ;
            }
            $.fn.textbox.call(jq, myopts);
            setTimeout(function(){
            	aotoCode(myopts);
            	/*输入框隐藏属性*/
            	var hidden = jq.attr("type")==='hidden';
            	if(hidden){
            		jq.next("span").hide();
            	}
            },100);
        });
    };
    
    /*子表渲染扩展开始*/
    $.parser.plugins.push("tablegrid");
    $.fn.tablegrid = function (options, param) {
    	var fn = {
    		res: null,
    		fieldName: null,
    		tableName: null,
    		url : '/console/jForm/rewrite/getDbGrid',
    		getColumns:function(rows){
    			var columns = [],rows = rows || [] ,row = null;
    			var fieldRequired = null;
				for(var i=0,len=rows.length ;i<len; i++){
					row = rows[i];
    				if(row.fieldEnabled!='Y'){ continue; }
    				var field = {field:row.fieldName, title:row.fieldTitle, width:100} ;
    				
    				if(row.fieldPlug=='隐藏属性'){
    					field.hidden = true;
    				}
    				columns.push(field);
				}
				return columns;
    		},
    		initGrid:function(columns){
    			var girdId = '#'+ this.fieldName ;
    			$(girdId).datagrid({
					fitColumns:true,
				    columns:[columns],
				    data: [ {id:''},{id:''}, {id:''} ],
				    onSelect:function(index, row){
				    	$(girdId).datagrid("beginEdit", index);
				    },
				    onLoadSuccess:function(data){
				    }
				});  
    		},
			_ajaxGrid:function(){
				var _this = this;
				$.getJSON(_this.url, {formId: _this.tableName } ,function(res){
					var columns = _this.getColumns(res.rows);
					_this.tableName = res.fTableName ;
					_this.res = res; 
					_this.initGrid(columns);
				});
			},
			start:function(){
				this._ajaxGrid();
			}
    	};
        //当options为字符串时，说明执行的是该插件的方法。
        if (typeof options == "string") { return $.fn.textbox.apply(this, arguments); }
        options = options || {};
        //当该组件在一个页面出现多次时，this是一个集合，故需要通过each遍历。
        return this.each(function () {
            var jq = $(this) , jqName = jq.attr("name") || jq.attr("id");
            var tableName = jq.attr("tablename");
            
            fn.tableName = tableName ;
            fn.fieldName = jqName ;
           
            var myopts = $.extend({}, $.fn.textbox.parseOptions(this), options);
            $.fn.textbox.call(jq, myopts);
            /*控件初始化及回显*/        
            setTimeout(function(){
            	 var textbox =  jq.parent().find(".textbox").css("border","0px");
     	         textbox.find(".textbox-text").hide();
     	         textbox.append('<div style="height:auto;" id="'+ jqName +'"></div>');
     	         
     	         fn.start();
            },100);
        });
    }
    /*子表渲染扩展结束*/
    
    
})(jQuery);